import React, { Component, PropTypes } from 'react'
import { helper } from '../utility'
import axios from 'axios'
import { message } from 'antd'

export default class LoginForm extends Component {
  constructor() {
    super()

    this.login = this.login.bind(this)

    this.state = {
      username: '',
      password: '',
    }
  }
  render() {
    return (
      <div className="rt-home-form">
        <p className="rt-username">
          <span>用户名</span>
        </p>
        <input
          className="rt-username-input"
          onChange={(e) => {
            this.setState({
              username: e.target.value,
            })
          }}
        />
        <div className="rt-password-box">
          <span className="rt-password">密码</span>
          <span className="rt-password-forget">忘记密码？</span>
        </div>
        <input
          className="rt-password-input"
          type="password"
          onChange={(e) => {
            this.setState({
              password: e.target.value,
            })
          }}
        />
        <div className="rt-operation">
          <div className="rt-checkbox">
            <input type="checkbox" />
            <span className="rt-checkbox-text"> 记住登录状态</span>
          </div>
          <span
            onClick={this.login}
            className="rt-login-text"
          >
            登 录
          </span>
        </div>
      </div>
    )
  }
  login() {
    const { username, password } = this.state
    const { router } = this.context
    const encryptedPassword = helper.encryption(password) + ''
    message.loading('正在处理...', 0)
    axios.post('/v1/login', {
        username,
        password, encryptedPassword,
      })
      .then(res => res.data)
      .then(data => {
        message.destroy()
        if (!data.error) {
          message.success('登录成功')
          router.push('/dashboard')
        }
        else {
          message.warning(data.message)
        }
      })
  }
}

LoginForm.contextTypes = {
  router: PropTypes.object,
}